//  ******************************************************************************
//  包引入
const express = require('express');
const app = express();
let cookieParser = require("cookie-parser");
let bodyParser = require("body-parser");
const Eureka = require('eureka-js-client').Eureka;
const request = require('request');
const eurekaUtils = require('./eureka-utils');

//  ******************************************************************************
//  中间件 注册
app.use(bodyParser.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({
    extended: false
}));


//  eureka
const client = new Eureka({
    // application instance information
    instance: {
        instanceId: 'eurekaid',
        app: 'jqservice',
        hostName: 'eurekatest',
        ipAddr: '172.16.115.74',
        statusPageUrl: 'http://localhost:5000',
        port: {
            '$': 5000,
            '@enabled': 'true',
        },
        vipAddress: 'jqservice',
        dataCenterInfo: {
            '@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',
            name: 'MyOwn',
        },
    },
    eureka: {
        // eureka server host / port
        host: '172.16.115.115',
        port: 8761,
        servicePath: '/eureka/apps/'
    }
});


client.logger.level('debug');
client.start(function (error) {
    console.log(error || 'complete');
    let instance = client.getInstancesByAppId("PRODUCCLIENT");
    console.log(instance.length);
    // let url = 'http://' + instance[0].ipAddr + ':' + instance[0].port['$']
    // console.log("url:",url);

    // request(url+'/merc/getPro',(err,res,body)=>{
    //     console.log('body:', body);
    // })
});



//  ******************************************************************************
//  路由注册
app.use((req, res, next) => { req.eurekaClient = client; next(); })
app.get('/health', (req, res) => {
    res.json({
        status: 'UP'
    });
});
app.get('/', (req, res, next) => {
    var bookmarkServer = eurekaUtils.getBookmarkRootUrl(req.eurekaClient);
    console.log('bookmarkServer:',bookmarkServer);
    request(bookmarkServer + '/prod/getProd',(err,res,req)=>{
        console.log('/prod/getProd',req);
    })
    res.json({
        status: true,
        message: "It's works!"
    });
});
app.get('/test', (req, res, next) => {
    res.json({
        status: true,
        message: "test's works!"
    });
});

app.listen(5000);